package com.ext.aic.utils.http;

import android.content.Context;

import com.ext.aic.apis.RequestServer;
import com.ext.aic.handler.RequestHandler;
import com.ext.aic.utils.http.cookie.CookieJarImpl;
import com.ext.aic.utils.http.cookie.store.SPCookieStore;
import com.hjq.http.EasyConfig;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Protocol;

public class HttpUtils {

    private static volatile HttpUtils instance;

    public static HttpUtils getInstance() {
        if (instance == null) {
            synchronized (HttpUtils.class) {
                if (instance == null) {
                    instance = new HttpUtils();
                }
            }
        }
        return instance;
    }

    private OkHttpClient client;
    private OkHttpClient.Builder builder;

    private OkHttpClient.Builder getBuilder(Context applicationContext) {
        if (builder == null) {
            builder = new OkHttpClient.Builder();
            builder.connectTimeout(30000, TimeUnit.MILLISECONDS);
            builder.readTimeout(30000, TimeUnit.MILLISECONDS);
            builder.writeTimeout(30000, TimeUnit.MILLISECONDS);
            builder.cookieJar(new CookieJarImpl(new SPCookieStore(applicationContext)));
            //添加证书信任
            SslSocketManager.SSLParams sslParams1 = SslSocketManager.getSslSocketFactory();
            if (sslParams1 != null) {
                builder.sslSocketFactory(sslParams1.sSLSocketFactory, sslParams1.trustManager);
            }
            builder.protocols(Collections.singletonList(Protocol.HTTP_1_1));
        }
        return builder;
    }

    public OkHttpClient getClient(Context applicationContext) {
        if (client == null) {
            OkHttpClient.Builder httpBuilder = getBuilder(applicationContext);
            client = httpBuilder.build();
        }
        return client;
    }

    public void init(Context applicationContext) {
        OkHttpClient httpClient = getClient(applicationContext);
        EasyConfig.with(httpClient)
                .setLogEnabled(false)
                .setServer(new RequestServer())
                .setHandler(new RequestHandler(applicationContext))
                .setRetryCount(3)
                .setInterceptor(new DynamicHostInterceptor())
                .into();
    }
}
